package cn.hpclub.server.controller.admin;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.JFinal;

import cn.hpclub.server.bean.SystemConfig;
import cn.hpclub.server.model.VgroupZFBG;
import cn.hpclub.server.util.ExcelLargeDataUtils;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.SystemConfigUtil;

public class VgroupZFBGController extends BaseAdminController<VgroupZFBG>{

    private static Logger       logger     = LoggerFactory.getLogger(VgroupZFBGController.class);
    private static final String ORG_LIST   = "orgList";
    private static final String ORG_ID     = "org_id";
    private static final String START_TIME = "startTime";
    private static final String END_TIME   = "endTime";

    public void list(){
        int defaultOrgId = iniOrgTree();
        // 0为搜索，1位导出
        String isExport = getPara("isExport");
        // 搜索字段
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        if(searchInfo.get(ORG_ID) == null){
            searchInfo.put(ORG_ID, String.valueOf(defaultOrgId));
        }
        if(searchInfo.get(START_TIME) == null){
            try{
                setDateParam(searchInfo);
            }
            catch(ParseException e){
                e.printStackTrace();
            }
        }

        String selectSql = VgroupZFBG.dao.getSelectSql();
        String expectSql = VgroupZFBG.dao.getExpectSql(searchInfo);

        if("1".equals(isExport)){
            try{
                export(selectSql, expectSql);
            }
            catch(IOException e){
                e.printStackTrace();
            }
        } else{
            query(searchInfo, selectSql, expectSql);
        }
    }

    private void query(ConcurrentHashMap<String, String> searchInfo, String select, String sqlExceptSelect){
        logger.info(select + " " + sqlExceptSelect);
        findByPageForSearch(select, sqlExceptSelect);
        setAttrs(searchInfo);
        render("/admin/vgroup_zfbg_list.tpl");
    }

    private void export(String select, String sqlExceptSelect) throws IOException{
        String[] headers = null;
        String[] columns = null;
        headers = new String[] { "资费名称", "资费编码", "用户号码", "店员姓名", "店员手机号", "地市 ", "区县 ", "渠道编码", "渠道名称", "渠道类型", "客户经理",
                "办理时间"/* , "办理来源" */ };
        columns = new String[] { "business_name", "business_code", "phone_no", "name", "user_name", "city", "area",
                "NumCode", "DisplayName", "sitetype", "is_accounts_manager",
                "create_time"/* , "sale_type" */ };
        String name = generateFileName();
        String filePath = getFilePath(name);
        JSONObject jo = null;
        try{
            String exportFileUrl = ExcelLargeDataUtils.exportData(headers, columns, select + sqlExceptSelect, name,
                                                                  filePath);
            jo = createDownloadSuccessJSONObject(exportFileUrl);
        }
        catch(IOException e){
            e.printStackTrace();
            jo = createDownloadErrorJSONObject(e);
        }
        renderJson(jo.toJSONString());
    }

    /**
     * @Title: createDownloadErrorJSONObject
     * @Description:TODO
     * @param e
     * @return JSONObject
     */

    private JSONObject createDownloadErrorJSONObject(IOException e){
        JSONObject jo = new JSONObject();
        jo.put("status", 0);
        jo.put("message", "导出失败：" + e.getMessage());
        return jo;
    }

    /**
     * @Title: createDownloadSuccessJsonObject
     * @Description:TODO
     * @param exportFileUrl
     *            void
     */

    private JSONObject createDownloadSuccessJSONObject(String exportFileUrl){
        JSONObject jo = new JSONObject();
        jo.put("status", 1);
        jo.put("message", "导出成功，点击下载");
        jo.put("url", exportFileUrl);
        renderJson(jo.toJSONString());
        return jo;
    }

    private String getFilePath(String name){
        String filePath = JFinal.me().getServletContext().getRealPath(SystemConfig.UPLOAD_FILE_DIR + name);

        String fileDir = SystemConfigUtil.getSystemConfig().getUploadDir();
        logger.debug("cmccbusiness fileDir = " + fileDir);

        if(!StringUtils.isEmpty(fileDir)){
            filePath = fileDir + "/file/" + name;
        }
        return filePath;
    }

    private String generateFileName(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HHmmssSSS");
        String curTime = sdf.format(date);
        String fileName = "V网资费变更办理清单" + curTime + ".xlsx";
        return fileName;
    }

    private int iniOrgTree(){
        List<Entry<String, String>> orgList = InterfaceUtil.getOrgList();
        setAttr(ORG_LIST, orgList);
        if(orgList.size() > 0){
            return Integer.parseInt(orgList.get(0).getValue());
        } else{
            return 0;
        }
    }

    private void setDateParam(ConcurrentHashMap<String, String> searchInfo) throws ParseException{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String endDate = sdf.format(new java.util.Date());
        Calendar c = Calendar.getInstance();
        c.setTime(sdf.parse(endDate));
        c.add(Calendar.MONTH, -1); // 得到前一个月
        String startDate = sdf.format(c.getTime());

        searchInfo.put(START_TIME, startDate);
        searchInfo.put(END_TIME, endDate);
    }
}
